<?php

namespace plugin\ycMassage\app\model;

use Exception;
use plugin\ycMassage\utils\enum\ActionIdentity;
use plugin\ycMassage\utils\enum\State;
use think\facade\Db;

class MassageUserDealer extends Model
{
    protected function user()
    {
        return $this->hasOne(MassageUser::class, 'id', 'uid');
    }
    protected function wallet()
    {
        return $this->hasOne(MassageUserWallet::class, 'uid', 'uid');
    }
    public static function commission($uid, $order, $transaction_freeze_period, $action = '')
    {
        $_config = getHpConfig('', $order->saas_appid, 'dealer');
        if (empty($_config) || $_config['state'] !== 'yes' || $_config[$action . 'level'] < 1) {
            return false;
        }
        $_config = [
            'level' => (int)$_config[$action . 'level'],
            'proportion' => (int)$_config[$action . 'proportion'],
            'proportion_level_1' => (int)$_config[$action . 'proportion_level_1'],
            'proportion_level_2' => (int)$_config[$action . 'proportion_level_2'],
            'proportion_level_3' => (int)$_config[$action . 'proportion_level_3'],
            'platform_commission' => (int)$_config[$action . 'platform_commission'],
        ];
        $user = MassageUser::where('id', $uid)->find();
        if (!$user) {
            return false;
        }
        $dealerPrice = $order->price * $_config['proportion'] / 100;
        $pData = [];
        for ($i = 1; $i <= $_config['level']; $i++) {
            $pData[] = [
                'saas_appid' => $user->saas_appid,
                'uid' => $user->id,
                'from_uid' => $action?$order->technician_id:$order->uid,
                'orders_id' => $order->id,
                'order_price' => $order->price,
                'order_proportion' => $_config['proportion'],
                'proportion_level' => $_config['proportion_level_' . $i],
                'price' => $dealerPrice * $_config['proportion_level_' . $i] / 100,
                'level' => $i,
                'create_time' => date('Y-m-d H:i:s')
            ];
            if (!$user->dealer_uid) {
                break;
            }
            $user = MassageUser::where('id', $user->dealer_uid)->find();
        }
        $level = ['', '一级', '二级', '三级'];
        $commission = 0;
        foreach ($pData as $key => $item) {
            $model = self::where(['uid' => $item['uid']])->find();
            if(!$model||$model->state != State::YES['value']){
                break;
            }
            if ($item['price']>0) {
                $model->order_num = Db::raw('order_num+1');
                $model->order_price = Db::raw('order_price+' . $item['order_price']);
                $model->save();
                $temp = $item;
                krsort($temp);
                MassageUserDealerLog::insert($temp);
                $remarks = $level[$item['level']] . '分销，订单ID：' . $order->id;
                if ($transaction_freeze_period) {
                    $MassageUserWallet = MassageUserWallet::where(['uid' => $item['uid']])->lock(true)->find();
                    if (!$MassageUserWallet) {
                        throw new Exception('用户钱包不存在');
                    }
                    $MassageUserFreezeMoney = new MassageUserFreezeMoney();
                    $MassageUserFreezeMoney->uid = $item['uid'];
                    $MassageUserFreezeMoney->form_uid =  $item['from_uid'];
                    $MassageUserFreezeMoney->saas_appid = $model->saas_appid;
                    $MassageUserFreezeMoney->action = ActionIdentity::DEALER['value'];
                    $MassageUserFreezeMoney->money = $item['price'];
                    $MassageUserFreezeMoney->orders_id = $order->id;
                    $MassageUserFreezeMoney->state = State::NO['value'];
                    $MassageUserFreezeMoney->unfreezing_time = date('Y-m-d H:i:s', strtotime("+{$transaction_freeze_period} hours"));
                    $MassageUserFreezeMoney->remarks = $remarks;
                    $MassageUserFreezeMoney->save();
                    $MassageUserWallet->channels_freeze_money = Db::raw('channels_freeze_money+' . $item['price']);
                    $MassageUserWallet->save();
                } else {
                    MassageUserDealerBill::increase($remarks, $item['uid'], $item['price'], $order->id);
                }
                $commission += $item['price'];
            }
        }
        if ($commission <= 0) {
            return 0;
        }
        $platform_commission = $_config['platform_commission'];
        return $commission - round($commission * $platform_commission / 100, 4);
    }
    public static function IncPeopleNum($uid)
    {
        $model = self::where(['uid' => $uid])->find();
        if ($model) {
            $model->people_num = Db::raw('people_num+1');
            $model->save();
        }
    }
}
